﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;


namespace FYPHP
{
    public partial class ProductDetails : System.Web.UI.Page
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["fyphp"].ConnectionString);
        String ProductUploadUserID;

        protected void Page_Load(object sender, EventArgs e)
        {

            conn.Open();
            SqlCommand cmdSearch, cmdView;
            SqlDataReader dtrSearch;

            //get product details
            cmdSearch = new SqlCommand("SELECT * FROM Products p, Users u, Category c WHERE p.p_category=c.cat_id AND p.u_id=u.u_id AND p.p_id=@id", conn);
            cmdSearch.Parameters.AddWithValue("@id", Request.QueryString["id"]);
            dtrSearch = cmdSearch.ExecuteReader();
            dtrSearch.Read();

            String positon = dtrSearch["u_position"].ToString();
            ProductUploadUserID = dtrSearch["u_id"].ToString();
            lblPname.Text = dtrSearch["p_name"].ToString();
            lblID.Text = dtrSearch["p_id"].ToString();
            lblSeller.Text = dtrSearch["username"].ToString();
            lblDesc.Text = dtrSearch["p_desc"].ToString();
            lblCat.Text = dtrSearch["cat_name"].ToString();
            lblView.Text = dtrSearch["p_views"].ToString();
            lblQuantity.Text = dtrSearch["p_quantity"].ToString();
            lblPrice.Text = dtrSearch["p_price"].ToString();
            dtrSearch.Close();

            if (positon == "ShopOwner")
                btnAddShoppingCart.Text = "Add to Shopping Cart";
            else if (positon == "Member")
                btnAddShoppingCart.Text = "Buy Now";


            //update product views
            cmdSearch = new SqlCommand("SELECT p_views FROM Products WHERE p_id = @pid", conn);
            cmdSearch.Parameters.AddWithValue("@pid", Request.QueryString["id"]);
            int pviews = Convert.ToInt32(cmdSearch.ExecuteScalar());
            pviews += 1;
            cmdView = new SqlCommand("UPDATE Products SET p_views = @pviews WHERE p_id = @pid", conn);
            cmdView.Parameters.AddWithValue("@pid", Request.QueryString["id"]);
            cmdView.Parameters.AddWithValue("@pviews", pviews);
            cmdView.ExecuteNonQuery();

            //add quantity to dropdown
            if (Convert.ToInt32(lblQuantity.Text) > 0)
            {
                for (int x = 1; x <= Convert.ToInt32(lblQuantity.Text); x++)
                    ddlQuantity.Items.Add("" + x);
            }
            else if (Convert.ToInt32(lblQuantity.Text) <= 0)
                ddlQuantity.Items.Add("0");

            //check quantity
            if (lblQuantity.Text == "0")
            {
                btnAddShoppingCart.Enabled = false;
                btnReserveProduct.Enabled = true;
            }
            else
            {
                btnAddShoppingCart.Enabled = true;
                btnReserveProduct.Enabled = false;
            }

            //Response.Write(ProductUploadUserID);

            if (Session["ID"] != null && Session["Role"] != null)
            {
                Panel1.Visible = true;
                lblUserName.Text = Session["Username"].ToString();
                lblUserID.Text = Session["ID"].ToString();
                // lblUserID.Visible = false;

                if (Session["ID"].ToString().Equals(ProductUploadUserID) || Session["Role"].ToString().Equals("Admin"))
                {
                    btnRemoveProduct.Visible = true;
                    btnEditProducts.Visible = true;
                    btnAddShoppingCart.Enabled = false;
                }
            }
            else
            {
                Panel1.Visible = false;
                btnAddShoppingCart.Enabled = false;
            }

            if (!IsPostBack)
            {

                //get comments
                SqlCommand cmdComment = new SqlCommand("SELECT * FROM Products p, Comments c, Users u WHERE c.u_id=u.u_id AND c.p_id=p.p_id AND c.p_id=@id ORDER BY c_date DESC", conn);
                cmdComment.Parameters.AddWithValue("@id", Request.QueryString["id"]);
                SqlDataReader dtrSearch1 = cmdComment.ExecuteReader();
                Repeater1.DataSource = dtrSearch1;
                Repeater1.DataBind();
                dtrSearch1.Close();
            }
                conn.Close();
        }

        public string getPic()
        {
            SqlCommand cmdSearch;
            SqlDataReader dtrSearch;
            conn.Open();

            cmdSearch = new SqlCommand("Select p_picture From Products Where p_id=@id", conn);
            cmdSearch.Parameters.AddWithValue("@id", Request.QueryString["id"]);
            dtrSearch = cmdSearch.ExecuteReader();

            dtrSearch.Read();
            String pic = dtrSearch["p_picture"].ToString();

            conn.Close();
            return pic;
        }

        protected void btnAddComment_Click(object sender, EventArgs e)
        {
            if (txtComment.Text == "")
            {
                MessageBox("Please enter some text to comment!");
            }
            else
            {
                SqlCommand cmdsearch, cmdAdd;
                conn.Open();

                cmdsearch = new SqlCommand("Select MAX(c_id) From Comments", conn);
                int cid = Convert.ToInt32(cmdsearch.ExecuteScalar());
                cid += 1;

                cmdAdd = new SqlCommand("INSERT INTO Comments VALUES (@cid, @pid, @uid, @desc, @date)", conn);
                cmdAdd.Parameters.AddWithValue("@cid", cid);
                cmdAdd.Parameters.AddWithValue("@pid", Request.QueryString["id"]);
                cmdAdd.Parameters.AddWithValue("@uid", Session["ID"].ToString());
                cmdAdd.Parameters.AddWithValue("@desc", txtComment.Text);


                cmdAdd.Parameters.AddWithValue("@date", DateTime.Now);
                int x = cmdAdd.ExecuteNonQuery();

                if (x == 1)
                {
                    MessageBox("Comment Successfully added!");
                    Redirect("ProductDetails.aspx?id=" + Request.QueryString["id"]);
                }
                conn.Close();
            }
        }

        private void MessageBox(string msg)
        {
            Label lbl = new Label();
            lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "')</script>";
            Page.Controls.Add(lbl);
        }

        private void Redirect(string msg)
        {
            Label lbl = new Label();
            lbl.Text = "<script language=\"javascript\">window.location='" + msg + "';</script>";
            Page.Controls.Add(lbl);
        }

        protected void AddShoppingCart_Click(object sender, EventArgs e)
        {
            int check;
            
            //If seller does not open shop

            if (btnAddShoppingCart.Text == "Buy Now")
            {
                SqlCommand cmdSearchTID, cmdInsert, cmdInsert2;
                conn.Open();
                
                //obtained the latest transaction id

                cmdSearchTID = new SqlCommand("Select MAX(t_id) from Transactions", conn);
                int t_id = Convert.ToInt32(cmdSearchTID.ExecuteScalar());
                t_id++;

                //Insert record into Transactions

                cmdInsert = new SqlCommand("Insert into Transactions Values(@TID,@UID,@SID,@Tseller,@T_Status,@T_Total,@Date)", conn);
                cmdInsert.Parameters.AddWithValue("@TID", t_id);
                cmdInsert.Parameters.AddWithValue("@UID", Convert.ToInt32(lblUserID.Text));
                cmdInsert.Parameters.AddWithValue("@SID", Convert.ToInt32("0"));
                cmdInsert.Parameters.AddWithValue("@Tseller", ProductUploadUserID);
                cmdInsert.Parameters.AddWithValue("@T_Status", "BuyNow");
                cmdInsert.Parameters.AddWithValue("@T_Total", Convert.ToDouble(ddlQuantity.Text) * Convert.ToDouble(lblPrice.Text));
                cmdInsert.Parameters.AddWithValue("@Date", DateTime.Now);
                cmdInsert.ExecuteNonQuery();

                //Insert record into Transactions Products (only 1 record)

                cmdInsert2 = new SqlCommand("Insert into Transactions_Products Values(@PID,@TID,@Quantity,@Date)", conn);
                cmdInsert2.Parameters.AddWithValue("@PID", Convert.ToInt32(lblID.Text));
                cmdInsert2.Parameters.AddWithValue("@TID", Convert.ToInt32(t_id));
                cmdInsert2.Parameters.AddWithValue("@Quantity", Convert.ToInt32(ddlQuantity.Text));
                cmdInsert2.Parameters.AddWithValue("@Date", DateTime.Now);
                cmdInsert2.ExecuteNonQuery();
                conn.Close();

                Session["ReferenceNumber"] = "REF" + String.Format("{0:00000}", t_id);
                Session["TotalOrder"] = Convert.ToDouble(ddlQuantity.Text) * Convert.ToDouble(lblPrice.Text);
                Session["SellerID"] = ProductUploadUserID.ToString();
                Session["TransactionID"] = t_id;


                Response.Redirect("ShippingDetail.aspx");
            }
            else if (btnAddShoppingCart.Text == "Add to Shopping Cart") //If the seller is a ShopOwner
            {
                SqlCommand cmdSearchTID, cmdCheck, cmdCheck2, cmdUpdate, cmdInsert, cmdInsert2, cmdItem, cmdCheckItem;
                SqlDataReader dtrCheck2, dtrCheckItem;
                conn.Open();

                //obtained the latest transaction id

                cmdSearchTID = new SqlCommand("Select MAX(t_id) from Transactions", conn);
                int t_id = Convert.ToInt32(cmdSearchTID.ExecuteScalar());

                //Check whether is there any record for This user in the transaction table where status is still cart 

                cmdCheck = new SqlCommand("Select COUNT(t_id) from Transactions WHERE u_id = '" + lblUserID.Text + "' AND t_status = 'Cart'", conn);
                check = Convert.ToInt32(cmdCheck.ExecuteScalar());

                if (check == 0) // if dun have any cart for this user 
                {
                    //Insert record into Transactions

                    t_id++;
                    cmdInsert = new SqlCommand("Insert into Transactions Values(@TID,@UID,@SID,@Tseller,@T_Status,@T_Total,@Date)", conn);
                    cmdInsert.Parameters.AddWithValue("@TID", t_id);
                    cmdInsert.Parameters.AddWithValue("@UID", Convert.ToInt32(lblUserID.Text));
                    cmdInsert.Parameters.AddWithValue("@SID", Convert.ToInt32("0"));
                    cmdInsert.Parameters.AddWithValue("@Tseller", ProductUploadUserID);
                    cmdInsert.Parameters.AddWithValue("@T_Status", "Cart");
                    cmdInsert.Parameters.AddWithValue("@T_Total", Convert.ToDouble(ddlQuantity.Text) * Convert.ToDouble(lblPrice.Text));
                    cmdInsert.Parameters.AddWithValue("@Date", DateTime.Now);
                    cmdInsert.ExecuteNonQuery();

                    //Insert record into Transactions Products (only 1 record)

                    cmdInsert2 = new SqlCommand("Insert into Transactions_Products Values(@PID,@TID,@Quantity,@Date)", conn);
                    cmdInsert2.Parameters.AddWithValue("@PID", Convert.ToInt32(lblID.Text));
                    cmdInsert2.Parameters.AddWithValue("@TID", Convert.ToInt32(t_id));
                    cmdInsert2.Parameters.AddWithValue("@Quantity", Convert.ToInt32(ddlQuantity.Text));
                    cmdInsert2.Parameters.AddWithValue("@Date", DateTime.Now);
                    cmdInsert2.ExecuteNonQuery();
                }
                else // if there is a cart for this user
                {
                    int check2;
                    double tTotal=0;

                    //Check whether the transactions table has any record for this user where the status is cart and buying from the same seller

                    cmdCheck = new SqlCommand("Select COUNT(t_id) from Transactions WHERE u_id = '" + lblUserID.Text + "' AND t_status = 'Cart' AND t_seller='"+ ProductUploadUserID +"'", conn);
                    check2 = Convert.ToInt32(cmdCheck.ExecuteScalar());

                    // Has cart but buy from Different Seller (Shop Owner)

                    if (check2 == 0) 
                    {
                        //Insert New record into the Transaction

                        t_id++;
                        cmdInsert = new SqlCommand("Insert into Transactions Values(@TID,@UID,@SID,@Tseller,@T_Status,@T_Total,@Date)", conn);
                        cmdInsert.Parameters.AddWithValue("@TID", t_id);
                        cmdInsert.Parameters.AddWithValue("@UID", Convert.ToInt32(lblUserID.Text));
                        cmdInsert.Parameters.AddWithValue("@SID", Convert.ToInt32("0"));
                        cmdInsert.Parameters.AddWithValue("@Tseller", ProductUploadUserID);
                        cmdInsert.Parameters.AddWithValue("@T_Status", "Cart");
                        cmdInsert.Parameters.AddWithValue("@T_Total", Convert.ToDouble(ddlQuantity.Text) * Convert.ToDouble(lblPrice.Text));
                        cmdInsert.Parameters.AddWithValue("@Date", DateTime.Now);
                        cmdInsert.ExecuteNonQuery();

                        //Inser New Record into the Transaction Product Table

                        cmdInsert2 = new SqlCommand("Insert into Transactions_Products Values(@PID,@TID,@Quantity,@Date)", conn);
                        cmdInsert2.Parameters.AddWithValue("@PID", Convert.ToInt32(lblID.Text));
                        cmdInsert2.Parameters.AddWithValue("@TID", Convert.ToInt32(t_id));
                        cmdInsert2.Parameters.AddWithValue("@Quantity", Convert.ToInt32(ddlQuantity.Text));
                        cmdInsert2.Parameters.AddWithValue("@Date", DateTime.Now);
                        cmdInsert2.ExecuteNonQuery();
                    }
                    else
                    {
                        // Has cart and buy from Same Seller (Shop Owner)

                        int check3;

                        //Check whether is there any record for this user where the status is cart and buy from the same seller and is  buying the same product

                        cmdItem = new SqlCommand("SELECT COUNT(t.t_id) FROM Transactions t, Transactions_Products tp WHERE t.t_id = tp.t_id AND u_id = '" + lblUserID.Text + "' AND t_status = 'Cart' AND tp.p_id = @id", conn);
                        cmdItem.Parameters.AddWithValue("@id", Request.QueryString["id"]);
                        check3 = Convert.ToInt32(cmdItem.ExecuteScalar());

                        // Has cart and buy from Same Seller (Shop Owner) and buy same product

                        if (check3 != 0)
                        {
                            //obtained the transaction id and the total

                            cmdCheck2 = new SqlCommand("Select t.t_id, t.t_total FROM Transactions t, Transactions_Products tp WHERE t.t_id = tp.t_id AND u_id = '" + lblUserID.Text + "' AND t_status = 'Cart' AND tp.p_id = @id", conn);
                            cmdCheck2.Parameters.AddWithValue("@id", Request.QueryString["id"]);
                            dtrCheck2 = cmdCheck2.ExecuteReader();
                            dtrCheck2.Read();

                            t_id = Convert.ToInt32(dtrCheck2["t_id"]);
                            tTotal = Convert.ToDouble(dtrCheck2["t_total"]);
                            dtrCheck2.Close();

                            //obtained the previous added product quantity and price

                            cmdCheckItem = new SqlCommand("SELECT tp.quantity, p.p_price FROM Products p, Transactions_Products tp WHERE tp.p_id = p.p_id AND tp.t_id=@tid AND tp.p_id = @pid", conn);
                            cmdCheckItem.Parameters.AddWithValue("@pid", Request.QueryString["id"]);
                            cmdCheckItem.Parameters.AddWithValue("@tid", t_id);
                            dtrCheckItem = cmdCheckItem.ExecuteReader();
                            dtrCheckItem.Read();
                             
                            //Using the Total minus for this previous added subtotal

                            tTotal = tTotal - (Convert.ToDouble(dtrCheckItem["quantity"]) * Convert.ToDouble(dtrCheckItem["p_price"]));
                            dtrCheckItem.Close();

                            //Update the latest quantity for the same product into Transaction_Products (Haven't update the total)
                            cmdUpdate = new SqlCommand("UPDATE Transactions_Products SET quantity = @quantity WHERE t_id = '" + t_id + "' AND p_id=@pid", conn);
                            cmdUpdate.Parameters.AddWithValue("@quantity", ddlQuantity.Text);
                            cmdUpdate.Parameters.AddWithValue("@pid", Request.QueryString["id"]);
                            cmdUpdate.ExecuteNonQuery();
                        }
                        else // Has cart and buy from Same Seller (Shop Owner) but buy different product
                        {
                            //obtained the transaction id and the total

                            cmdCheck2 = new SqlCommand("Select t.t_id, t.t_total FROM Transactions t, Transactions_Products tp WHERE t.t_id = tp.t_id AND t.u_id = '" + lblUserID.Text + "' AND t.t_status = 'Cart' AND t.t_seller='"+ ProductUploadUserID +"'", conn);
                            dtrCheck2 = cmdCheck2.ExecuteReader();
                            dtrCheck2.Read();

                            t_id = Convert.ToInt32(dtrCheck2["t_id"]);
                            tTotal = Convert.ToDouble(dtrCheck2["t_total"]);
                            dtrCheck2.Close();

                            //Insert record into Transactions Products

                            cmdInsert2 = new SqlCommand("Insert into Transactions_Products Values(@PID,@TID,@Quantity,@Date)", conn);
                            cmdInsert2.Parameters.AddWithValue("@PID", Convert.ToInt32(lblID.Text));
                            cmdInsert2.Parameters.AddWithValue("@TID", Convert.ToInt32(t_id));
                            cmdInsert2.Parameters.AddWithValue("@Quantity", Convert.ToInt32(ddlQuantity.Text));
                            cmdInsert2.Parameters.AddWithValue("@Date", DateTime.Now);
                            cmdInsert2.ExecuteNonQuery();
                        }
                        double total = (Convert.ToDouble(ddlQuantity.Text) * Convert.ToDouble(lblPrice.Text)) + tTotal;

                        cmdUpdate = new SqlCommand("UPDATE Transactions SET t_total = @total WHERE t_id = '" + t_id + "'", conn);
                        cmdUpdate.Parameters.AddWithValue("@total", total);
                        cmdUpdate.ExecuteNonQuery();
                    }
                }

                conn.Close();
                MessageBox("The item is successfully added into the cart.");
                Redirect("ShopCart.aspx");
            }
        }

        protected void ReserveProduct_Click(object sender, EventArgs e)
        {
            try
            {
                SqlCommand cmdInsert;
                conn.Open();

                cmdInsert = new SqlCommand("Insert into Reservation Values(@PID,@UID,@Date)", conn);
                cmdInsert.Parameters.AddWithValue("@PID", lblID.Text);
                cmdInsert.Parameters.AddWithValue("@UID", Session["ID"].ToString());
                cmdInsert.Parameters.AddWithValue("@Date", DateTime.Now);
                cmdInsert.ExecuteNonQuery();
                conn.Close();
                Response.Redirect("ProductReservation.aspx");
            }
            catch (SqlException ex)
            {

            }
        }

        protected void btnRemoveProduct_Click(object sender, EventArgs e)
        {
            try
            {
                SqlCommand cmdRemove;
                conn.Open();

                cmdRemove = new SqlCommand("UPDATE Products SET p_status = @pstatus WHERE p_id = @pid", conn);
                cmdRemove.Parameters.AddWithValue("@pstatus", "Removed");
                cmdRemove.Parameters.AddWithValue("@pid",lblID.Text);
                cmdRemove.ExecuteNonQuery();
                conn.Close();

                Response.Redirect("ProductsList.aspx");
            }
            catch (SqlException ex)
            {

            }

        }

        protected void Repeater1_ItemCommand(Object Sender, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "DeleteComment")
            {

                int cid = Convert.ToInt32(e.CommandArgument.ToString());

                SqlCommand cmdDeleteComment;

                conn.Open();
                cmdDeleteComment = new SqlCommand("Delete from Comments Where c_id=@CID", conn);
                cmdDeleteComment.Parameters.AddWithValue("@CID", cid.ToString());

                int x = cmdDeleteComment.ExecuteNonQuery();

                conn.Close();

                if (x == 1)
                {
                    MessageBox("Comment Successfully deleted!");
                    Redirect("ProductDetails.aspx?id=" + Request.QueryString["id"]);
                }

            }
        }

        protected void btnEditProducts_Click(object sender, EventArgs e)
        {
            Response.Redirect("ProductEdit.aspx?id=" + lblID.Text);
        }




        protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (Session["Role"] != null && Session["ID"] != null) // got things
            {
                // not admin and not seller
                if (!(Session["Role"].ToString().Equals("Admin")) && !(Session["ID"].ToString().Equals(ProductUploadUserID)))
                {
                    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                    {
                        Button btn = new Button();
                        btn = (Button)e.Item.FindControl("btnDeleteComment");
                        btn.Visible = false;
                    }
                }
            }
            else // no log in
            {
               
                    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                    {
                        Button btn = new Button();
                        btn = (Button)e.Item.FindControl("btnDeleteComment");
                        btn.Visible = false;
                    }
                
            }
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            txtComment.Text = "";
        }

     

    }
}